/**
 * Copyright 2018 jianggujin (www.jianggujin.com).
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jianggujin.modulelink.mvc.upload;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.apache.tomcat.util.http.fileupload.ProgressListener;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import org.apache.tomcat.util.http.fileupload.servlet.ServletRequestContext;

import com.jianggujin.modulelink.util.JDefaultMultiValueMap;
import com.jianggujin.modulelink.util.JLogFactory;
import com.jianggujin.modulelink.util.JLogFactory.JLog;
import com.jianggujin.modulelink.util.JMultiValueMap;
import com.jianggujin.modulelink.util.JStringUtils;

/**
 * commons-fileupload的实现
 * 
 * @author jianggujin
 *
 */
public class JApacheMultipartResolver implements JMultipartResolver, ProgressListener {
    protected final JLog logger = JLogFactory.getLog(getClass());

    private final DiskFileItemFactory factory;
    private final ServletFileUpload upload;
    private final JMultipartResolverConfig config;

    public JApacheMultipartResolver(JMultipartResolverConfig config) {
        this.config = config;
        this.factory = new DiskFileItemFactory();
        this.factory.setSizeThreshold(config.getSizeThreshold());
        if (config.getRepository() != null) {
            if (!config.getRepository().exists() && !config.getRepository().mkdirs()) {
                throw new IllegalArgumentException(
                        "Given repository [" + config.getRepository() + "] could not be created");
            }
            this.factory.setRepository(config.getRepository());
        }
        this.upload = new ServletFileUpload(this.factory);
        this.upload.setSizeMax(config.getSizeMax());
        if (!JStringUtils.isBlank(config.getEncoding())) {
            this.upload.setHeaderEncoding(config.getEncoding());
        }
        this.upload.setFileSizeMax(config.getFileSizeMax());
        if (config.getProgressListener() != null) {
            this.upload.setProgressListener(this);
        }
    }

    protected JMultipartParsingResult parseFileItems(List<FileItem> fileItems) {
        JMultiValueMap<String, JMultipartFile> multipartFiles = new JDefaultMultiValueMap<String, JMultipartFile>();
        Map<String, String[]> multipartParameters = new HashMap<String, String[]>();

        // Extract multipart files and multipart parameters.
        for (FileItem fileItem : fileItems) {
            if (fileItem.isFormField()) {
                String value;
                if (config.getEncoding() != null) {
                    try {
                        value = fileItem.getString(config.getEncoding());
                    } catch (UnsupportedEncodingException ex) {
                        if (logger.isWarnEnabled()) {
                            logger.warn("Could not decode multipart item '" + fileItem.getFieldName()
                                    + "' with encoding '" + config.getEncoding() + "': using platform default");
                        }
                        value = fileItem.getString();
                    }
                } else {
                    value = fileItem.getString();
                }
                String[] curParam = multipartParameters.get(fileItem.getFieldName());
                if (curParam == null) {
                    // simple form field
                    multipartParameters.put(fileItem.getFieldName(), new String[] { value });
                } else {
                    // array of simple form fields
                    String[] newParam = JStringUtils.addStringToArray(curParam, value);
                    multipartParameters.put(fileItem.getFieldName(), newParam);
                }
            } else {
                // multipart file field
                JApacheMultipartFile file = new JApacheMultipartFile(fileItem);
                multipartFiles.add(file.getName(), file);
                if (logger.isDebugEnabled()) {
                    logger.debug("Found multipart file [" + file.getName() + "] of size " + file.getSize()
                            + " bytes with original filename [" + file.getOriginalFilename() + "], stored "
                            + file.getStorageDescription());
                }
            }
        }
        return new JMultipartParsingResult(multipartFiles, multipartParameters);
    }

    @Override
    public JMultipartParsingResult resolveMultipart(HttpServletRequest request) throws JMultipartException {
        if (request != null && ServletFileUpload.isMultipartContent(request)) {
            try {
                // this.upload.parseParameterMap(request);
                return parseFileItems(this.upload.parseRequest(new ServletRequestContext(request)));
            } catch (FileUploadException e) {
                throw new JMultipartException("Parse multipart error.", e);
            }
        }
        return null;
    }

    @Override
    public void update(long pBytesRead, long pContentLength, int pItems) {
        config.getProgressListener().update(pBytesRead, pContentLength, pItems);
    }

}
